<script setup lang="ts">
import { getActivityDetailsApi, getInvitationApi } from '@/services/my'
import { useMemberStore, useLocationStore } from '@/stores'
import { PageSkip, Toast } from '@/utils/tools'
import { computed, reactive, ref } from 'vue'
import { onShow, onUnload } from '@dcloudio/uni-app'
import { getCountdownCouponsApi, getMiniJinGangApi, getToNewApi } from '@/services/home'
import { getRaffleApi } from '@/services/raffle'
import { useThrottle } from '@/hooks/useDebounce'
import Personage from './Personage.vue'

const locationStore = useLocationStore()
const memberStore = useMemberStore()
// 渲染数据
const bonusList = ref<any[]>([{}, {}])
/**
 *   点击跳转前进行判断用户数据是否存在，
 *  数据不存在调用登录弹窗
 */
const skipPageFn = async (item: any) => {
  console.log(11111111111111)
  // 未登录情况
  const notLogin = item.name === '社群福利' || item.name === '合作加盟' || item.name === '券包专区'
  // 已登录情况
  const login = <any>[
    { val: '邀请好友', api: getInvitationApi },
    { val: '吃饭打卡', api: getActivityDetailsApi },
    // { val: '抽奖有礼', api: getRaffleApi },
  ]
  if (notLogin) {
    PageSkip(item.pageUrl)
  } else {
    const logVal = login.find((i: any) => i.val === item.name)
    if (memberStore.token && logVal) {
      const res = await logVal.api({ cityName: locationStore.location?.cityName })
      if (res.code === 222) {
        Toast('活动已失效')
      } else if (res.code === 223 || res.code === 224) {
        Toast('活动未开始')
      } else if (res.code === 200) {
        ;(item.name === '邀请好友' && res?.data?.marketingId) ||
        (item.name === '抽奖有礼' && res?.data?.lotteryId)
          ? PageSkip(item.pageUrl)
          : item.name === '吃饭打卡' && res?.data
          ? PageSkip(item.pageUrl)
          : Toast('活动还未开始')
      } else {
        Toast('活动还未开始')
      }
    } else if (memberStore.token) {
      PageSkip(item.pageUrl)
    } else {
      emit('open')
    }
  }
}
const emit = defineEmits<{
  (e: 'open'): void
  (e: 'unfinishedOpen'): void
}>()
const throttledSkipPageFn = useThrottle(skipPageFn, 1000)
/** 节流跳转 */
const skipThrottle = (item: any) => {
  throttledSkipPageFn(item)
}

const getMiniJinGang = async () => {
  const res = await getMiniJinGangApi()
  bonusList.value = res?.data || []
  bonusList.value = bonusList.value.filter((item: any) => {
    return item.status
  })
}

onShow(() => {
  getMiniJinGang()
  if (!memberStore.token) return
  getToNew()
  getCountdownCoupons()
})

/** 获取领券中心的上新 */
const getToNew = async () => {
  const reslut = await getToNewApi()
  show_new.value = reslut.data || false
}
const show_new = ref(false)

const couponInfo = reactive<{
  discounts: string
  discountsType: string
  validEndTime: number
  type: number
}>({
  discounts: '',
  discountsType: '',
  validEndTime: 0,
  type: 0,
})
let distance = ref()
const countdownText = ref()
/** 获取首页倒计时的优惠券信息 */
const getCountdownCoupons = async () => {
  try {
    const res = await getCountdownCouponsApi()
    console.log(res)
    couponInfo.type = res.data?.type
    couponInfo.discounts = res.data?.discounts
    couponInfo.discountsType = res.data?.discountsType === 1 ? '元' : '折'
    couponInfo.validEndTime = new Date(res.data?.validEndTime).getTime()
    startCountdown()
  } catch (error) {
    console.log(error)
  }
}
let countdown = ref<any>()
/**倒计时 */
const startCountdown = () => {
  countdown.value = setInterval(() => {
    if (!couponInfo.validEndTime && !distance.value) {
      clearInterval(countdown.value)
      return
    }
    const _newDate = new Date().getTime()
    distance.value = couponInfo.validEndTime - _newDate
    if (distance.value > 0) {
      const hours = Math.floor((distance.value % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((distance.value % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((distance.value % (1000 * 60)) / 1000)
      countdownText.value = `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`
    } else {
      clearInterval(countdown.value)
    }
  }, 1000)
}
/**补零 */
function padZero(num: number) {
  return num.toString().padStart(2, '0')
}

const formatBounsUrl = computed(() => {
  return (title: string) => {
    const item = bonusList.value.find((i: any) => {
      return i.name === title
    })
    return item
  }
})

onUnload(() => {
  clearInterval(countdown.value)
})

const handleOpen = () => {
  emit('open')
}
</script>

<template>
  <view class="orderModule">
    <view class="Module_top">
      <navigator hover-class="none" open-type="switchTab" url="/pages/eat/eat" class="_leftBox"
        ><image class="icon" src="/static/images/home_icon_1.png" mode="aspectFit" /><text
          class="order_top"
          >自动点餐</text
        >
        <text class="order_bottom">自助点餐 免排队</text>
        <view v-if="couponInfo.type === 5 && distance" class="_endDate">
          {{ `霸王免单券优惠倒计时${countdownText}` }}
        </view>
        <view v-else-if="couponInfo.type !== 5 && distance" class="_endDate">{{
          `${couponInfo.discounts + couponInfo?.discountsType}优惠倒计时${countdownText}`
        }}</view>
      </navigator>
      <navigator hover-class="none" open-type="switchTab" url="/pages/goods/goods" class="_rightBox"
        ><image class="icon" src="/static/images/home_icon_2.png" mode="aspectFit" /><text
          class="takeMeals_top"
          >快速取餐</text
        >
        <text class="takeMeals_bottom">&nbsp;&nbsp;取餐快 快取餐</text>
      </navigator>
    </view>
    <Personage @open="handleOpen" ref="PersonageRef" class="Personage" />
  </view>
  <view class="Module_bottom" :class="bonusList?.length <= 6 ? 'Module_bottom_between' : ''">
    <view
      @tap.stop="skipThrottle(item)"
      class="bonusItem"
      v-for="item in bonusList"
      :key="item.imgUrl"
    >
      <image class="bonusItem_image" :src="formatBounsUrl(item.name)?.imgUrl" mode="scaleToFill" />
      <text>{{ formatBounsUrl(item.name)?.name }}</text>
      <!-- <BjsCornerMark
          v-show="isCouponNum && index === 2 && _value"
          :value="_value"
          :backgroundColor="'#FF4E21'"
        /> -->
      <view class="_New" v-if="show_new && item.name === '领券中心'">上新 </view>
    </view>
  </view>
</template>

<style lang="scss">
.orderModule {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 376rpx;
  background-color: #fff;
  border-radius: 16rpx;
  font-family: 'PingFangSC';
  box-shadow: 0px 2rpx 12rpx 2rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
  border-bottom: 12rpx solid $uni-color-motif;
  .Module_top {
    display: flex;
    justify-content: space-around;
    width: calc(100% - 34px);
    height: 240rpx;
    padding: 48rpx 0;
    margin: 0 36rpx;
    align-items: center;
    // margin: 0 36rpx;
    border-bottom: 2rpx solid #dfdfdf;

    ._leftBox,
    ._rightBox {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 50%;
      height: 100%;
      .icon {
        width: 66rpx;
        height: 66rpx;
      }
      .order_top,
      .takeMeals_top {
        margin-top: 8rpx;
        width: 100%;
        text-align: center;
        font-size: 28rpx;
        font-weight: 600;
      }
      .order_bottom,
      .takeMeals_bottom {
        color: var(--font-color-light-50, rgb(133, 133, 133));
        font-family: 'PingFang SC';
        font-size: 22rpx;
      }
      ._endDate {
        margin-top: 8rpx;
        min-width: 40rpx;
        color: #ff4e21;
        text-align: center;
        font-size: 22rpx;
      }
    }
    ._leftBox {
      border-right: 2rpx solid #dfdfdf;
    }
  }
}
.Module_bottom {
  display: flex;
  height: 220rpx;
  overflow-x: auto;
  width: 700rpx;
  justify-content: flex-start;
  padding: 24rpx 44rpx 24rpx;
  align-items: center;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0px 2rpx 12rpx 2rpx rgba(0, 0, 0, 0.1);
  margin-top: 30rpx;
  &::-webkit-scrollbar {
    display: none !important;
    width: 0;
    height: 0;
    color: transparent;
  }
  .bonusItem {
    position: relative;
    width: 120rpx;
    // height: 132rpx;
    font-family: 'PingFang SC';
    font-size: 26rpx;
    font-weight: 400;
    text-align: center;
    margin-right: 56rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    &:last-of-type {
      margin-right: 0;
    }
    .bonusItem_image {
      width: 52rpx;
      height: 52rpx;
      // background: linear-gradient(180deg, #d5f0d8, #d5f0d800);
      margin-bottom: 8rpx;
    }
    ._New {
      position: absolute;
      top: 0;
      right: 0;
      width: 60rpx;
      height: 32rpx;
      line-height: 32rpx;
      transform: translate(50%);
      color: #fff;
      background-color: #ff4e21;
      border: 4rpx solid #fff;
      border-radius: 16rpx 0px;
      box-sizing: content-box;
    }
  }
}
.Module_bottom_between {
  justify-content: space-between;
}
</style>
